package com.ly1.aicosplay.service;

import com.ly1.aicosplay.domain.po.Character;
import com.ly1.aicosplay.config.CharacterFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatMemoryService {
    
    private final ChatClient chatClient;
    private final ChatMemory chatMemory;
    private final CharacterFactory characterFactory;
    
    @Autowired
    public ChatMemoryService(ChatClient.Builder chatClientBuilder,
                             ChatMemory chatMemory,
                             CharacterFactory characterFactory) {
        this.chatClient = chatClientBuilder.build();
        this.chatMemory = chatMemory;
        this.characterFactory = characterFactory;
    }
    
    /**
     * 与角色进行带上下文记忆的对话
     * @param conversationId 会话ID
     * @param characterId 角色ID
     * @param message 用户消息
     * @return AI回复
     */
    public String chatWithMemory(String conversationId, String characterId, String message) {
        Character character = characterFactory.getCharacterById(characterId);
        if (character == null) {
            throw new RuntimeException("角色不存在");
        }
        
        // 构建角色扮演的系统提示词
        String systemPrompt = buildCharacterPrompt(character);
        
        // 获取之前的对话历史
        List<Message> history = chatMemory.get(conversationId);
        
        // 使用ChatClient进行对话
        String response = chatClient.prompt()
                .system(systemPrompt)
                .messages(history)
                .user(message)
                .call()
                .content();
        
        // 手动管理聊天记忆
        chatMemory.add(conversationId, new UserMessage(message));
        chatMemory.add(conversationId, new AssistantMessage(response));
        
        return response;
    }
    
    /**
     * 构建角色扮演提示词
     * @param character 角色对象
     * @return 系统提示词
     */
    private String buildCharacterPrompt(Character character) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你现在扮演的角色是: ").append(character.getName()).append("\n");
        prompt.append("角色描述: ").append(character.getDescription()).append("\n");
        prompt.append("背景故事: ").append(character.getBackground()).append("\n");
        prompt.append("性格特点: ").append(character.getPersonality()).append("\n");
        prompt.append("特殊技能: ");
        if (character.getSpecialSkills() != null) {
            prompt.append(String.join(", ", character.getSpecialSkills()));
        }
        prompt.append("\n");
        prompt.append("请以该角色的身份和用户对话，保持角色一致性。");
        
        return prompt.toString();
    }
}